﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using com.codeplex.eatoutadvocate.Web.Mvc.Models;
using com.codeplex.eatoutadvocate.Web.Mvc.Services;
using com.codeplex.eatoutadvocate.Web.Mvc.Utility;
using System.Web.Routing;

namespace EatOutAdvocate.Web.Mvc.Controllers
{
    [Authorize]
    public class RecommendController : Controller
    {
        private EatOutAdvocateService _recommendService { get; set; }
        private LocationService _locationService { get; set; }
        private WeatherService _weatherService { get; set; }
        protected override void Initialize(RequestContext requestContext)
        {
            if (_recommendService == null)
                _recommendService = new EatOutAdvocateService();

            if (_locationService == null)
                _locationService = new LocationService();

            if (_weatherService == null)
                _weatherService = new WeatherService();

 	         base.Initialize(requestContext);
        }


        public ActionResult Index()
        {

            EatOutModel eo = new EatOutModel();
            return View(eo);
        }

        [HttpPost]
        public ActionResult Result(EatOutModel eo)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    long userId = -1;
                    long.TryParse(Session["FacebookUserId"].ToString(), out userId);
                    if (-1 == userId)
                    {
                        // TODO: Log user out
                    }
                    string zipcode = eo.ZipCode;
                    string appkey = ConfigurationManager.AppSettings["WeatherAppKey"].ToString();
                    _weatherService.Populate(zipcode, appkey);
                    eo.Weather = (int)_weatherService.GetWeather();
                    eo.Temperature = (int)_weatherService.GetTemperature();
                    eo.Time = DateTime.Now.Hour;
                    List<string> recommendation = _recommendService.Recommend(userId, eo);

                    ViewBag.Message = recommendation.ElementAt(0); // First restaurant *top rank*
                    return View();
                }
                catch (Exception exp)
                {
                    LogUtility.ProcessException("Recommend",exp.Message.ToString());
                    return View("~/Views/Shared/Error.cshtml");
                }
            }
            else
            {
                return View("Index", eo);
            }
        }

    }
}
